import * as echarts from 'echarts';
import { is2DArray, deepClone, colorLuminance } from '@/utils/index';

const line_basic = ({
  seriesData = [],
  seriesName = '',
  cursor = 'auto',
  labelColor = '#00ffff',
  axisColor = '#00ffff',
  color = [
    // '#5470c6',
    '#66a6ff',
    '#91cc75',
    '#fac858',
    '#ee6666',
    '#73c0de',
    '#3ba272',
    '#fc8452',
    '#9a60b4',
    '#ea7ccc',
  ],
  unit = '',
  xAxisData,
  xAxisUnit = '',
  xAxisRotate = false,
  yAxisMultiple = false,
  lineStyle = [],
  areaStyle = [],
  smooth = false,
  showSymbol = true,
  legend = true,
  avgLine = true,
  dataZoom = false,
}) => {
  // 计算平均值
  let computedAverage = (data) => {
    let combined = data.map((value) => Number(value));
    let average = (combined.reduce((acc, val) => acc + val, 0) / combined.length).toFixed(0);
    return average;
  };
  // 平均值线配置
  let markLineOption = (average) => {
    return {
      data: [
        {
          // type: 'average',
          name: '平均值',
          yAxis: average,
        },
      ],
      silent: false,
      label: {
        position: 'end',
        formatter: '平均值\n' + average,
        fontSize: 14,
        width: '50',
        overflow: 'break',
      },
      lineStyle: {
        type: 'dashed',
      },
    };
  };
  // Y轴配置
  let yAxisOption = {
    name: unit && `（${unit}）`,
    nameTextStyle: {
      color: axisColor,
    },
    type: 'value',
    // min: 'dataMin',
    // max: 'dataMax',
    min: function (value) {
      //取最小值向下取整为最小刻度
      let integer = Math.floor(value.min * 0.97);
      if (value.min < 0) integer = Math.floor(value.min / 0.97);
      let length = String(Math.abs(integer)).length;
      return Math.floor(integer / Math.pow(10, length - 2)) * Math.pow(10, length - 2);
    },
    max: function (value) {
      //取最大值向上取整为最大刻度
      let integer = Math.ceil(value.max / 0.97);
      if (value.max < 0) integer = Math.ceil(value.max * 0.97);
      let length = String(Math.abs(integer)).length;
      return Math.ceil(integer / Math.pow(10, length - 2)) * Math.pow(10, length - 2);
    },
    axisLabel: {
      show: true,
      color: axisColor,
      // formatter: `{value} ${unit}`,
    },
    axisLine: {
      show: true,
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: '#666',
        type: 'dashed',
        opacity: 0.5,
      },
    },
  };
  let yAxis = [];
  if (yAxisMultiple) {
    seriesData.forEach((item) => {
      yAxis.push(yAxisOption);
    });
  } else yAxis.push(yAxisOption);

  // 系列配置
  let series = [];
  let seriesItemOption = {
    name: '',
    type: 'line',
    data: null,
    cursor: cursor,
    smooth: smooth,
    showSymbol: showSymbol,
    symbol: 'circle',
    symbolSize: 6,
    emphasis: { focus: 'series' },
    lineStyle: {
      width: 2,
      type: 'solid',
    },
  };
  // seriesData为二维数组时,设置多个series
  if (is2DArray(seriesData)) {
    seriesData.forEach((item, index) => {
      const seriesItem = deepClone(seriesItemOption);
      // 如果 seriesName 是数组 分别设置 name、areaStyle
      if (Array.isArray(seriesName)) {
        seriesItem.name = seriesName[index];
        seriesItem.areaStyle = areaStyle[index];
        if (lineStyle.length) seriesItem.lineStyle = lineStyle[index];
      } else seriesItem.name = seriesName;
      // 显示平均值线
      if (avgLine) {
        seriesItem.markLine = markLineOption(computedAverage(item));
        // 调整平均值亮度
        seriesItem.markLine.label.color = colorLuminance(color[index], 50);
        seriesItem.markLine.lineStyle.color = colorLuminance(color[index], 50);
      }
      seriesItem.data = item;
      if (yAxisMultiple) seriesItem.yAxisIndex = index;
      series.push(seriesItem);
    });
    // seriesData为普通数组时,设置一个series
  } else {
    const seriesItem = deepClone(seriesItemOption);
    // 显示平均值线
    if (avgLine) {
      seriesItem.markLine = markLineOption(computedAverage(seriesData));
      seriesItem.markLine.label.color = colorLuminance(Array.isArray(color) ? color[0] : color, 50);
      seriesItem.markLine.lineStyle.color = colorLuminance(Array.isArray(color) ? color[0] : color, 50);
    }
    seriesItem.name = seriesName;
    seriesItem.data = seriesData;
    series.push(seriesItem);
  }

  const defaultConfig = {
    // animationDuration: 3000,
    tooltip: {
      confine: true,
      trigger: 'item',
      formatter: (params) => {
        let content = '';
        // 标记线 markLine 的自定义内容 (trigger: 'item' 才能显示)
        if (params.componentType == 'markLine') {
          seriesName = '';
          content =
            `<span">${params.name}</span><br />` +
            `<span style="display:inline-block; margin-right:4px; border-radius:10px;` +
            `width:10px; height:10px; background-color:${params.borderColor};"></span>` +
            `${seriesName}&nbsp;&nbsp;<span style="font-weight:bold;">${params.value} ${unit}</span><br />`;
        } else {
          let seriesName = params.seriesName;
          if (seriesName == 'series\u00000') seriesName = '';
          content =
            `<span">${params.name}${xAxisUnit}</span><br />` +
            `${params.marker}${seriesName}&nbsp;&nbsp;` +
            `<span style="font-weight:bold;">${params.value} ${unit}</span><br />`;
          // params有多个，是数组时
          if (Array.isArray(params)) {
            content = params.reduce((pre, item, index) => {
              let seriesName = item.seriesName;
              if (seriesName == 'series\u00000') seriesName = '';
              let row_str = '';
              if (item.value !== '' && item.value !== null && item.value !== undefined) {
                row_str =
                  `${item.marker}${seriesName}&nbsp;&nbsp;<span style="font-weight:bold;">` +
                  `${item.value} ${item.value === '' ? '' : unit}</span><br />`;
              }
              if (index == 0) row_str = `<span">${item.name}${xAxisUnit}</span><br />` + row_str;
              return pre + row_str;
            }, '');
          }
        }
        return content;
      },
    },
    legend: legend && {
      itemWidth: 35,
      itemWHeight: 10,
      top: -2,
      textStyle: {
        fontSize: 13,
        color: labelColor,
      },
    },
    color: color,
    xAxis: {
      name: xAxisUnit && `（${xAxisUnit}）`,
      nameLocation: 'start',
      nameGap: 2,
      nameTextStyle: {
        color: axisColor,
        verticalAlign: 'top',
        lineHeight: 30,
      },
      axisLine: {
        onZero: false,
      },
      type: 'category',
      data: xAxisData,
      axisLabel: {
        show: true,
        fontSize: 12,
        color: axisColor,
        align: xAxisRotate ? 'center' : null,
        interval: xAxisRotate ? 0 : 'auto',
        rotate: xAxisRotate ? 25 : 0,
        margin: xAxisRotate ? 20 : 8,
      },
      // 设置 trigger: 'axis' 显示 series tooltip,
      axisPointer: {
        show: true,
        type: 'line',
        label: {
          show: false,
        },
        lineStyle: {
          width: 0.5,
        },
      },
    },
    yAxis: yAxis,
    // yAxis: {
    //   name: `（${unit}）`,
    //   nameTextStyle: {
    //     color: axisColor,
    //   },
    //   type: 'value',
    //   // min: 'dataMin',
    //   // max: 'dataMax',
    //   min: function (value) {
    //     //取最小值向下取整为最小刻度
    //     let integer = Math.floor(value.min * 0.97);
    //     if (value.min < 0) integer = Math.floor(value.min / 0.97);
    //     let length = String(Math.abs(integer)).length;
    //     return Math.floor(integer / Math.pow(10, length - 2)) * Math.pow(10, length - 2);
    //   },
    //   max: function (value) {
    //     //取最大值向上取整为最大刻度
    //     let integer = Math.ceil(value.max / 0.97);
    //     if (value.max < 0) integer = Math.ceil(value.max * 0.97);
    //     let length = String(Math.abs(integer)).length;
    //     return Math.ceil(integer / Math.pow(10, length - 2)) * Math.pow(10, length - 2);
    //   },
    //   axisLabel: {
    //     show: true,
    //     color: axisColor,
    //     // formatter: `{value} ${unit}`,
    //   },
    //   axisLine: {
    //     show: true,
    //   },
    //   splitLine: {
    //     show: true,
    //     lineStyle: {
    //       color: '#666',
    //       type: 'dashed',
    //     },
    //   },
    // },
    grid: {
      top: '30',
      left: '5',
      right: avgLine ? '60' : '8',
      bottom: dataZoom ? '15' : '5',
      containLabel: true,
    },
    dataZoom: dataZoom && [
      {
        type: 'slider',
        // height: 10,
        // bottom: 10,
        start: 0, //默认为0  可设置滚动条从在后进行展示
        end: 30, //默认为100
        show: true,
        xAxisIndex: [0],
        handleSize: 0, //滑动条的 左右2个滑动条的大小
        height: 0, //组件高度
        left: '5%', //左边的距离
        right: '5%', //右边的距离
        bottom: 10, // 底边的距离
        borderColor: '#0f1b3b',
        fillerColor: '#0f1b3b',
        backgroundColor: '#2b55ac', //两边未选中的滑动条区域的颜色
        showDataShadow: false, //是否显示数据阴影 默认auto
        showDetail: false, //即拖拽时候是否显示详细数值信息 默认true
        // 移动滑块样式
        moveHandleIcon: 'none',
        moveHandleSize: 5,
        moveHandleStyle: {
          // color: '#003378',
          color: '#184dde',
        },
      },
    ],
    series: series,
  };
  if (xAxisRotate) defaultConfig.grid.bottom = defaultConfig.grid.bottom - 15;

  const opt = deepClone(defaultConfig);
  return opt;
};

export default {
  line_basic,
};
